package com.xusheng.cli.controller.back;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xusheng.cli.common.annotation.OperationLogAnno;
import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.Result;
import com.xusheng.cli.common.enums.OperationType;
import com.xusheng.cli.common.validation.Save;
import com.xusheng.cli.common.validation.Update;
import com.xusheng.cli.entity.userModule.AdminMenuVO;
import com.xusheng.cli.entity.userModule.AssociatedRoleDTO;
import com.xusheng.cli.entity.userModule.PasswordDTO;
import com.xusheng.cli.entity.userModule.User;
import com.xusheng.cli.service.UserService;
import com.xusheng.cli.tools.CurrentUserUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * 总后台用户表(User)表控制层
 *
 * @author jy
 * @since 2022-01-17 12:08:46
 */
@Validated
@RestController
@RequestMapping("/api/v1/account")
public class UserController {

    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    @GetMapping("getIpWhitelist")
    public Result<String> getIpWhitelist() {
        return Result.success(userService.getIpWhitelist(CurrentUserUtil.getUserId()));
    }

    @OperationLogAnno(module = "账户表模块", type = OperationType.UPDATE, desc = "修改当前登录人二级密码")
    @PutMapping("setSecondPassword")
    public Result<Object> setSecondPassword(@RequestBody Map<String, String> secondPassword) {
        User user = userService.getById(CurrentUserUtil.getUserId());
        if (StrUtil.isNotBlank(user.getSecondPassword())) {
            if (StrUtil.isBlank(secondPassword.get("oldPassword"))) {
                return Result.error("请输入原密码");
            } else {
                boolean b = DigestUtil.bcryptCheck(secondPassword.get("oldPassword"), user.getSecondPassword());
                if (b) {
                    user.setSecondPassword(DigestUtil.bcrypt(secondPassword.get("newPassword")));
                    return Result.isSuccess(userService.updateById(user));
                } else {
                    return Result.error("原密码错误");
                }
            }
        } else {
            user.setSecondPassword(DigestUtil.bcrypt(secondPassword.get("newPassword")));
            return Result.isSuccess(userService.updateById(user));
        }
    }

    /**
     * 校验二级密码
     *
     * @param password
     * @return
     */
    @GetMapping("checkSecondPassword")
    public Result<Object> checkSecondPassword(String password) {
        User user = userService.getById(CurrentUserUtil.getUserId());
        if (StrUtil.isBlank(user.getSecondPassword())) {
            return Result.error("该账号尚未设置二级密码，请先设置二级密码");
        } else {
            boolean b = DigestUtil.bcryptCheck(password, user.getSecondPassword());
            if (b) {
                return Result.success();
            } else {
                return Result.error("二级密码错误");
            }
        }
    }

    @OperationLogAnno(module = "账户表模块", type = OperationType.UPDATE, desc = "修改当前登录人ip白名单")
    @PutMapping("setIpWhitelist")
    public Result<Object> setIpWhitelist(@RequestBody Map<String, String> ipWhitelist) {
        return Result.isSuccess(userService.setIpWhitelist(ipWhitelist.get("ip")));
    }

    @OperationLogAnno(module = "账户表模块", type = OperationType.UPDATE, desc = "修改当前登录人密码")
    public Result<Object> setPassword(@RequestBody PasswordDTO passwordDTO) {
        return Result.isSuccess(userService.setPassword(passwordDTO));
    }

    @PostMapping("associatedRole")
    @OperationLogAnno(module = "账户表模块", type = OperationType.UPDATE, desc = "用户关联角色")
    public Result<Object> associatedRole(@RequestBody AssociatedRoleDTO associatedRoleDTO) {
        return Result.isSuccess(userService.associatedRole(associatedRoleDTO));
    }

    @PutMapping("disOrEnaAccount")
    @OperationLogAnno(module = "账户表模块", type = OperationType.UPDATE, desc = "启禁用账户")
    public Result<Object> disOrEnaAccount(@NotNull(message = "账号id不能为空") Long accountId) {
        return Result.isSuccess(userService.disOrEnaAccount(accountId));
    }

    /**
     * 获取当前登录人菜单
     *
     * @author jy
     * @since 2022/1/18 10:47
     */
    @GetMapping("menu")
    public Result<List<AdminMenuVO>> getMenuList() {
        return Result.success(userService.getMenuList());
    }

    /**
     * 查询当前登录人信息
     *
     * @author jy
     * @since 2022/1/18 10:47
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo() {
        return Result.success(userService.getById(CurrentUserUtil.getUserId()));
    }

    /**
     * 查询所有数据
     *
     * @param user 查询实体
     * @return 所有数据
     * @author jy
     * @since 2022-01-17 12:08:46
     */
    @GetMapping("queryAll")
    public Result<List<User>> queryAll(User user) {
        user.setEnable(true);
        return Result.success(userService.list(new QueryWrapper<>(user)));
    }

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param user 查询实体
     * @return 所有数据
     * @author jy
     * @since 2022-01-17 12:08:46
     */
    @GetMapping("queryByPage")
    public Result<MyPage<User>> queryByPage(MyPage<User> page, User user) {
        return Result.success(userService.page(page, new QueryWrapper<>(user)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     * @author jy
     * @since 2022-01-17 12:08:46
     */
    @GetMapping("queryOne/{id}")
    public Result<User> selectOne(@PathVariable Serializable id) {
        return Result.success(userService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param user 实体对象
     * @return 新增结果
     * @author jy
     * @since 2022-01-17 12:08:46
     */
    @PostMapping("insert")
    @OperationLogAnno(module = "账户表模块", type = OperationType.CREATE, desc = "新增数据")
    public Result<Object> insert(@Validated(Save.class) @RequestBody User user) {
        return Result.isSuccess(userService.insert(user));
    }

    /**
     * 修改数据
     *
     * @param user 实体对象
     * @return 修改结果
     * @author jy
     * @since 2022-01-17 12:08:46
     */
    @PutMapping("update")
    @OperationLogAnno(module = "账户表模块", type = OperationType.UPDATE, desc = "修改数据")
    public Result<Object> update(@Validated(Update.class) @RequestBody User user) {
        return Result.isSuccess(userService.update(user));
    }

    /**
     * 删除单条数据
     *
     * @param id 主键
     * @return 删除结果
     * @author jy
     * @since 2022-01-17 12:08:46
     */
    @DeleteMapping("delete/{id}")
    @OperationLogAnno(module = "账户表模块", type = OperationType.DELETE, desc = "删除单条数据")
    public Result<Object> delete(@PathVariable Long id) {
        User user = new User();
        LambdaUpdateWrapper<User> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(User::getId, id).eq(User::getInitial, false);
        return Result.isSuccess(userService.deleteWithFill(user, updateWrapper));
    }

    /**
     * 批量删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     * @author jy
     * @since 2022-01-17 12:08:46
     */
    @DeleteMapping("batchDelete")
    @OperationLogAnno(module = "账户表模块", type = OperationType.DELETE, desc = "批量删除数据")
    public Result<Object> batchDelete(@Validated @Size(min = 1, message = "缺少删除所需的id") @RequestParam("idList") List<Long> idList) {
        User user = new User();
        user.setInitial(false);
        return Result.isSuccess(userService.batchDelete(idList, user));
    }

    /**
     * @author jy
     * @since 2020-07-15 14:50:59
     */
    @PutMapping("/setInitAccount")
    @OperationLogAnno(module = "账户表模块", type = OperationType.UPDATE, desc = "批量设置内置账户")
    public Result<Object> setInitAccount(@RequestBody List<Long> idList) {
        return Result.isSuccess(userService.setInitAccount(idList));
    }

    /**
     * 获取全部内置账户id
     *
     * @author jy
     * @since 2020-07-15 14:50:59
     */
    @GetMapping("/listInitAccount")
    public Result<List<Object>> listInitAccount() {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getInitial, true).eq(User::getEnable, true);
        queryWrapper.select(User::getId);
        return Result.success(userService.listObjs(queryWrapper));
    }

    /**
     * 获取修改当前登录人密码的验证码
     *
     * @author jy
     * @since 2022/1/18 10:47
     */
    @GetMapping("verificationCode")
    public void verification(HttpServletResponse response) {
        userService.getVerification(response);
    }

}

